package com.project.platformuser.user.service;

import com.project.platformcommon.Bean.EmailBean;
import com.project.platformcommon.constants.Constants;
import com.project.platformcommon.exception.PlatformException;
import com.project.platformcommon.kafka.EmailProducer;
import com.project.platformcommon.utils.Common;
import com.project.platformuser.user.dao.UserInfoMapper;
import com.project.platformuser.user.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {


    @Autowired
    private UserInfoMapper mapper;

    @Autowired
    private StringRedisTemplate template;


    @Autowired
    private EmailProducer producer;



    @Override
    @Transactional
    public void registerUser(UserInfo user){
        try {
            UserInfo repeatedUser = mapper.selectByEmail(user.getEmail());
            if(repeatedUser!=null){
                throw new PlatformException("账号已存在！");
            }
            //todo 并设置 注册状态
            int id = mapper.insertSelective(user);
            //存入redis 缓存 一个随机验证码  key为用户id
            String verNumber = Common.fourDigitRandom();
            template.opsForValue().set(id + "",verNumber, 60 * 10 , TimeUnit.SECONDS);
            EmailBean emailBean = new EmailBean();
            emailBean.setVerCode(verNumber);
            emailBean.setRecipient(user.getEmail());
            producer.sendVerCodeProducer(emailBean);
        }catch (Exception e){
            log.error("用户注册异常："+e);
            throw e;
        }
    }

    @Override
    public void setUserActStatus(UserInfo user) {

    }
}
